package srzy.common

import scala.util.parsing.combinator._
import scala.util.matching.Regex
import sun.font.TrueTypeFont

object TnsParser extends RegexParsers {

  def ` ` = """[ ]+""".r
  def `+-` = """[+-]""".r

  def str: Parser[String] = """[A-Za-z0-9_.]*""".r ^^ { _.toString }
  def int: Parser[Int] = """[0-9]*""".r ^^ { _.toInt }

  def group1: Parser[List[(String, String)]] = "(" ~ str ~ "=" ~ str ~ ")" ^^
    { case f1 ~ s1 ~ f2 ~ s2 ~ f3 => List((s1, s2)) }

  def group2: Parser[List[(String, String)]] = "(" ~ str ~ "=" ~ repsep(group1 | group2, "") ~ ")" ^^
    { case f1 ~ s1 ~ f2 ~ s2 ~ f3 => s2.flatMap(x => x) }

  def group3: Parser[(String, Map[String, String])] = str ~ "=" ~ repsep(group2, "") ^^
    { case s1 ~ f1 ~ s2 => (s1, s2.flatMap(x => x).toMap) }

  def group4: Parser[Map[String, Map[String, String]]] = repsep(group3, "") ^^
    { case s => s.toMap }

  //  def group3: Parser[List[(String, String)]] = "(" ~ str ~ "=" ~ repsep(group2 | group3, "") ~ ")" ^^
  //    { case f1 ~ s1 ~ f2 ~ s2 ~ f3 => s2.flatMap(x => x) }
  //
  //  def group4: Parser[List[(String, String)]] = str ~ "=" ~ repsep(group2 | group3, "") ~ ^^ { case f1 ~ s1 ~ f2 ~ s2 ~ f3 => s2.flatMap(x => x) }

  //  def group2: Parser[Map[String, (String, List[Int])]] = repsep(group1, ";") ^^
  //    { case g => g.toMap }

  //  def group3: Parser[Map[String, Map[String, (String, List[Int])]]] = repsep(group2, "^") ^^
  //    { case s => s.toMap }
  //: Map[String, List[(String, String)]]
  def parse(text: String) = {
    parseAll(group4, text) match {
      case Success(r, _) => r
      case Failure(msg, _) => throw new Exception("TNS Parser failure :" + msg)
      case Error(msg, _) => throw new Exception("TNS Parser error :" + msg)
    }
  }

}